package yunjiao.javatutorials.guava.base.functional;

import com.google.common.base.Equivalence;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 缓存键的创建
 *
 * @author yangyunjiao
 */
public class CacheWithFunctionalEquivalence {
    public record UserRequest(String userId, String action, Map<String, String> parameters) {
        // 基于用户ID和动作创建缓存键
        public String getCacheKey() {
            return userId + ":" + action;
        }
    }

    public static void main(String[] args) {
        // 创建基于缓存键的等价关系
        Equivalence<UserRequest> cacheKeyEquivalence =
                Equivalence.equals().onResultOf(UserRequest::getCacheKey);

        // 使用该等价关系创建缓存
        Cache<Equivalence.Wrapper<UserRequest>, String> cache =
                CacheBuilder.newBuilder()
                        .expireAfterWrite(10, TimeUnit.MINUTES)
                        .build();

        UserRequest request1 = new UserRequest("user123", "getProfile",
                Map.of("lang", "en"));
        UserRequest request2 = new UserRequest("user123", "getProfile",
                Map.of("lang", "fr")); // 相同用户和动作，不同参数

        // 存储缓存
        cache.put(cacheKeyEquivalence.wrap(request1), "Cached data for user123 profile");

        // 检索缓存 - 即使参数不同，但缓存键相同
        String cachedData = cache.getIfPresent(cacheKeyEquivalence.wrap(request2));
        System.out.println("缓存数据: " + cachedData);
    }
}
